/*
 * BrianClarkeCPE301Design3.c
 *
 * Created: 3/13/2014 9:43:42 PM
 *  Author: Iguana
 */ 
#include <avr/io.h>
#include <avr/interrupt.h>

int EdgeCount = 0;					// Falling Edge Counter
int TotalEdge = 32;					// To verify that 16 complete cycles have occurred

void EdgeCounter()
{
	PORTD ^= 1<<7;					// Toggle 7th bit on PortD for timer1 to catch
	EdgeCount++;					// Increment the edge count
	if (EdgeCount==TotalEdge)		// If there have been a total of 16 cycles
	{
		PORTD ^= 1<<6;				// Set the 9th bit of the LED bar [10th is for the ClockView]
		EdgeCount = 0;				// Clear the edge counter
	}
}

ISR(TIMER1_OVF_vect)				// Every 10 Cycles, check for 16 falling edges
{
	EdgeCounter();
}

void DirectINIT()		// Initialize the direction of used Ports [PORTB] and [PORTD]
{
	DDRB  = 0xFF;		// Set the direction for LED bits 0-7 [PORTB]
	DDRD  = 0xc0;		// Set the direction for LED bits 6 and 7 [PORTD] pin 6 is every 16 cycles, bit 7 is the ClockView
	PORTB = 0x00;		// Empty PORTB
	PORTD = 0x00;		// Empty PORTD
}

void TimerINIT()		// Initialize the timer bits [Timer1]
{
	TCCR1A = 0x00;		// Clear all bits
	TCCR1B = 0x02; 		// Set the CS prescaler to divide the clock by 8, creating 1/16th of a second overflows for quicker viewing
	TCCR0B = 0x06;		// Reads an external clock on the falling edge
}


int main(void)
{
	PORTB ^= TCNT0; 	// Set Timer0 clock to PORTB, this will trigger on every Timer1 overflow
	DirectINIT();		// Sets the Port directions
	TimerINIT();		// Sets the Timer bits
	
	EICRA = 0x02; 		// Sets the interrupts on the falling edge.
	TIMSK1 = 1; 		// Enables overflow interrupts.
	sei(); 				// Enables interrupts
	
	while(1)
	{					// Loop until interrupt
	}
}